import { getProductName, networkConfigTypes } from '@/config/product';
import { setDeviceOnboardingDeploy, stopDeviceOnboarding } from '@/services/gizwitsSdk';
// eslint-disable-next-line no-unused-vars
import Base, { IBaseConfigNetworkInitProps, IConfigNetworkParam } from '../base/baseConfigNetwork';
import deviceListModel from '@/models/deviceList';

import language from '@/models/language';

export default class SoftApConifg extends Base {
  isStart = false

  constructor(props: IBaseConfigNetworkInitProps) {
    console.log('SoftAp constructor');
    super(props);
    this.type = networkConfigTypes.TNetworkConfigTypeSoftAp;
    this.configTips = props.productConfig.softAp;
  }

  async startConfig(params?: IConfigNetworkParam) {
    if (!params) {
      return {};
    }
    super.startConfig(params);
    this.isStart = true;
    const { wifiName, password, timeout } = params;
    const data = await setDeviceOnboardingDeploy(
      {
        ssid: wifiName,
        key: password,
        mode: 0, // softAp配网
        timeout: timeout || 100,
        gagentTypes: [],
        softAPSSIDPrefix: this.productConfig.softAPSSIDPrefix,
        isBind: false
      }
    );

    if (data.success) {
      // 30s 超时
      const startTime = Date.now();
      while (true) {
        const res = await deviceListModel.getDeviceList();
        console.debug('setDeviceOnboardingDeploy devices', res.data);

        const now = Date.now(); // 当前时间戳（毫秒）

        const target = res.data?.find(item => {
          // 处理 create_time 可能为秒或毫秒
          const createTime = item.create_time * 1000;
          return (createTime > now - 60 * 1000);
        });
        
        if (target) {
          // 修改默认名称
          const productName = getProductName(target.product_key, language.key);

          const mac_address = target.mac.substring(target.mac.length - 4)
          const name = `${productName || target.mac}-${mac_address}`
          deviceListModel.renameDevice({ device: target, name });
          target.name = name;
          target.productKey = target.product_key;
          return {
            success: true,
            message: 'SUCCESS',
            data: [target]
          }
        }
        if (!this.isStart) {
          break;
        }
        if (Date.now() - startTime > 30000) {
          return {success: false, message: 'TIMEOUT'}
        }
        await new Promise(resolve => setTimeout(resolve, 2000));
      }
    }
  }

  endConfig() {
    this.isStart = false;
    stopDeviceOnboarding();
  }
}
